package com.xnyzc.lhy.finance.config;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * 支付宝配置和实现方法
 */
@Slf4j
@Configuration
@EnableCaching
public class AlipayConfig {

    /**支付宝应用id：入参app_id*/
    public static final String APPID = "2021002125669022";

    /**收款支付宝用户ID。如果该值为空，则默认为商户签约账号对应的支付宝用户ID */
    public static final String SELLER_ID = "";

    /**支付宝账户登录授权业务：入参target_id值 */
    public static final String TARGET_ID = "";
    /** 私钥 */
    public static final String RSA_PRIVATE = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCtLiq4hyoiQa+DPVb+vqJvlFVc21a0BflPboSJcCXD7ZD9cOQTQBA6oas0Es3+cqWSoFHU6mkHO1Zd1gxdEtIr/0ApACH4IYxv6rzGEteDG0E3fBmD+QqvXsEvofOvgRdY+hV7bnFw5lkgaClu0CXnikai/INUFFbRBcRHnRxycOHw57rfSu4WpslTFKla6CAYerQng1OoKJ6jyLmfnB3s8E3SM2d1YGayUUwE4n12Bs1ik2IOjJw50IKeJKkbw5KtlzMnG9H5bmUedc7lzItJsBi8+AOgsUPq7RWI76JngJlHyVAfvqra7KijEC+Jc0M6h7asK9lQJFISWojETf4jAgMBAAECggEACSVIAki5E+gOIcsqffeJUoUt4OKAeK9cFDLM8wkmJWu1XX0Jvm6CrOX+yZg4orhhQBYRXEIo28XpcLkuG/gzezlWpROpt5Xl+b8Wyws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viz8oBTYfOyU4o8BU45zbULis3ZBj/tAymLcS6wxO8zM=";
    /** 默认网关 */
    public static final String PAY_DEFAULT_URL = "https://openapi.alipay.com/gateway.do";
    /** 支付宝公钥，由支付宝生成 */
    public static final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnx+Vyi3Baeuehk/qjjC6/DLObyenuKxglrUfWpaxZqgm6fxUDQv3CvLgxLsQqVAwbq/SWbz8aR3F1eG/s44KwQ7RcJiLDg5GsxASSwMG+QlVAqZHuazazyxZW4DpFlsf4yfLGDFXOCqjYMN6nLl31zeNAJbtcZI+t4wa9YaJ7batn6dtgbN3q0+JtnZTVIqFifi6g16dhL6QEMz66ZjHQwwUF8BLY0l9EYscvB2pQEQynI0DkqWs9p8fUOaFoiZb9IC7PgBSj+qGGa3z2DvDnOzCm0UlH7ZlicD3+9hBZcd14ElZpPBDm+HLVIFoz51ErZSt9suQ6K75ywqg38wJBQIDAQAB";

    /**
     * 获取支付宝唯一userId 和 换取授权访问令牌
     * @param tokenCode 授权码，用户对应用授权后得到。
     * @return
     */
    public static String getAlipayUserIdAndAccessToken(String tokenCode) {
        //返回信息体
        StringBuffer bodyAll =  new StringBuffer();
        AlipayClient alipayClient = new DefaultAlipayClient(PAY_DEFAULT_URL,APPID,RSA_PRIVATE,"json","GBK",
                ALIPAY_PUBLIC_KEY,"RSA2");
        try{
            AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
            request.setGrantType("authorization_code");
            request.setCode(tokenCode);
            AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                String accessToken = response.getAccessToken();
                System.out.println("调用成功 accessToken:" + accessToken);
                if(null != accessToken){
                    //获取支付宝会员授权信息
                    String userBody = getAlipayUserInfo(accessToken);
                    if(null != userBody){
                        bodyAll.append(userBody);
                        System.out.println("body -->" + bodyAll);
                    }
                }
            } else {
                return null;
            }
        }catch (AlipayApiException e){
            log.info("获取支付宝唯一userId和换取授权访问令牌异常--->" + e.getMessage());
        }
        return bodyAll.toString();
    }

    /**
     * 获取支付宝会员授权信息
     * @param accessToken 访问令牌。通过该令牌调用需要授权类接口
     * @return
     */
    public static  String getAlipayUserInfo(String accessToken){
        //返回信息体
        StringBuffer body = new StringBuffer();
        AlipayClient alipayClient = new DefaultAlipayClient(PAY_DEFAULT_URL,APPID,RSA_PRIVATE,"json","GBK",
                ALIPAY_PUBLIC_KEY,"RSA2");
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
        try{
            AlipayUserInfoShareResponse response = alipayClient.execute(request,accessToken);
            if(response.isSuccess()){
                //支付宝用户的userId
                String user_id = response.getUserId();
                //用户昵称
                String nick_name = response.getNickName();
                body.append(user_id);
                body.append(",");
                body.append(nick_name);
            } else {
                return null;
            }
        }catch (AlipayApiException e){
            log.info("获取支付宝会员授权信息异常--->" + e.getMessage());
        }
        return body.toString();
    }

    //开发测试使用
    public static void main(String[] args){
        //一次性使用，不管成功失败
        String tokenCode = "1abaa37fe78140f49b91225ea50cZC66";
        String userInfo = getAlipayUserIdAndAccessToken(tokenCode);
        System.out.println("userInfo : " + userInfo);
    }
}
